import { update, info } from '@/api/cache'

const state = {
  props: null
}

const mutations = {
  SET_CACHE: (state, { key, value }) => {
    if (typeof value === 'string') {
      value = JSON.parse(value)
    }
    state[key] = value
  }
}

const actions = {
  getAndSetCache({ state, commit }, key) {
    if (state[key]) {
      return Promise.resolve()
    } else {
      return info(key).then(res => {
        if (res && res.data && res.data.value) {
          commit('SET_CACHE', { key, value: res.data.value })
          return true
        } else {
          return false
        }
      })
    }
  },
  saveCache({ commit }, { key, value }) {
    return update({ key, value }).then(res => {
      if (res && res.data && res.data.value) {
        commit('SET_CACHE', { key, value: res.data.value })
        return true
      } else {
        return false
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
